#include "MainWindow.h"
#include "ui_MainWindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    socket = NULL;
    setWindowTitle("Zigbus UDP Tester");
    connect(ui->sendButton, SIGNAL(clicked()), this, SLOT(onSendButtonClicked()));
    connect(ui->openCloseButton, SIGNAL(clicked()), this, SLOT(open()));
    connect(ui->clearButton, SIGNAL(clicked()), ui->consoleEdit, SLOT(clear()));
}

MainWindow::~MainWindow()
{
    delete ui;
    close();
}


void MainWindow::open()
{
    qDebug() << "[Zigbus] opening port...";
    socket = new QUdpSocket(this);
    connect(socket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
    if(!socket->bind(7756)) {
        qDebug() << "[Zigbus] ERROR: fail to listen UDP port 7756";
        qDebug() << socket->errorString();
        if(socket != NULL) {
            delete socket;
            socket = NULL;
        }
        return;
    }
    qDebug() << "[Zigbus] Now listening UDP port 7756";
    ui->openCloseButton->setText("Disconnect");
    disconnect(ui->openCloseButton, SIGNAL(clicked()), this, SLOT(open()));
    connect(ui->openCloseButton, SIGNAL(clicked()), this, SLOT(close()));
    return;
}

void MainWindow::close()
{
    qDebug() << "[Zigbus] closing port...";
    if(socket != NULL) {
        if(socket->isOpen())
            socket->close();
        delete socket;
        socket = NULL;
    }
    qDebug() << "[Zigbus] port closed";
    ui->openCloseButton->setText("Connect");
    disconnect(ui->openCloseButton, SIGNAL(clicked()), this, SLOT(close()));
    connect(ui->openCloseButton, SIGNAL(clicked()), this, SLOT(open()));
}

void MainWindow::onSendButtonClicked()
{
    qDebug() << "Button Send clicked";
    QString message = ui->messageEdit->text().trimmed();
    //if(socket != NULL && socket->isOpen()) {
        QByteArray datagram = message.toLocal8Bit();
        qDebug() << "[Zigbus] send message: " << message;
        socket->writeDatagram(datagram.data(), datagram.size(), QHostAddress("192.168..0.100"), 7755);
    //}
}

void MainWindow::readPendingDatagrams()
{
    qDebug() << "reading pending datagrams";
    while (socket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(socket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
        socket->readDatagram(datagram.data(), datagram.size(),
                                &sender, &senderPort);
        QString trame = datagram;
        qDebug() << "packet read: " << trame;
        ui->consoleEdit->appendPlainText(trame);
    }
}
